import { WebSocket } from "ws";
import { User } from "../../../types/User";
import { roomsTable } from "../../../database/rooms-table";
import { conversionMessage } from "../helpers/message-converter";
import { SetHerosMessageData } from "../types/MessageData";
import { Hero } from "../../../types/Hero";
import { Skill } from "../../../types/Skill";
import { shuffle } from "../utils/shuffle";

export const setHerosHandler = ({ user, payload }: { client: WebSocket; user: User; payload: SetHerosMessageData["payload"] }) => {
	const room = roomsTable.rooms.find((v) => v.roomId == payload.roomId);
	const player = room?.players.find((v) => v.user.userId == user.userId);
	if (room && player) {
		const heros = shuffle([...room.heros, ...player.heros.splice(0, player.heros.length)]);
		room.heros.length = 0;
		room.heros.push(...heros);
		const selectedHeros = [] as Hero[];
		payload.heroIds.forEach((heroId) => {
			const index = room.heros.findIndex((v) => v.heroId == heroId);
			if (index !== -1) {
				const hero = room.heros.splice(index, 1)[0];
				selectedHeros.push(hero);
				player.heros.push(hero);
			}
		});
		player.currentHerosSkinId = player.heros.map((v) => v.skins[0].skinId);
		player.hiddenHeroIds = player.heros.map((v) => v.heroId);
		player.healthLimit = Math.floor(player.heros.reduce((sum, v) => sum + v.healthLimit, 0) / player.heros.length);
		player.health = Math.floor(player.heros.reduce((sum, v) => sum + v.health, 0) / player.heros.length);
		player.skills = player.heros.reduce((sum, v) => sum.concat(v.skills), [] as Skill[]);
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "setedHeros", payload: { roomId: room.roomId, userId: user.userId, heros: selectedHeros } })));
		const log = { userId: user.userId, username: user.username, log: "设置了" + player.heros.length + "张武将。" };
		room.logs.push(log);
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "roomLog", payload: log })));
	}
};
